package net.sourceforge.cath.logging;

import net.sourceforge.cath.appender.Appender;
import net.sourceforge.cath.context.GlobalTransaction;
import net.sourceforge.cath.context.LoggingUnit;
import net.sourceforge.cath.logging.appender.file.FileAppender;

public class Logger {
	Appender appender;
	public final static String HEADER="CATH";
	public final static String FILENAME=System.getProperty("cathlog");
	static Logger instance = null;
	public static Logger getInstance()
	{
	
		if(instance ==null){
			instance = new Logger();
			// Initialize Logger
			Appender fileAppender = null;
			try{
				String filename="./cath.log";
				if(FILENAME==null || FILENAME.length()<1) filename="./cath.log";
				else filename=FILENAME;
				fileAppender = new FileAppender(filename);
				instance.setAppender(fileAppender);
				instance.info("File Appender has been initialized");
			}catch(Exception e){
				instance.error("Cannot create file appender");
				e.printStackTrace();
			}
		}
		return instance;
	}

	public Appender getAppender() {
		return appender;
	}
	public void setAppender(Appender appender) {
		this.appender = appender;
	}
	public void startLocalTransaction(LoggingUnit unit){
		appender.log(LogFormatter.formatStartLocalTransaction(unit));
	}
	public void endLocalTransaction(LoggingUnit unit){
		appender.log(LogFormatter.formatEndLocalTransaction(unit));
	}
	public void startGlobalTransaction(GlobalTransaction gtx)
	{
		appender.log(LogFormatter.formatStartGlobalTransaction(gtx));
	}
	public void endGlobalTransaction(GlobalTransaction gtx){
		appender.log(LogFormatter.formatEndGlobalTransaction(gtx));
		
	}
	public void log(String log){
		appender.log(HEADER+" "+log+"\n");
	}
	
	public void flush(){
		try{
			appender.flush();
		}catch(Exception e){
			error("appender flush failed");
			e.printStackTrace();
		}
	}
	public void info(String str){
		System.err.println(HEADER+" info:"+str);
	}
	public void warning(String str){
		//System.err.println(HEADER+" warning:"+str);
	}
	public void error(String str){
		System.err.println(HEADER+" error:"+str);
	}
	public void debug(String str){
		//System.err.println(HEADER+" debug:"+str);
	}
}
